package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.system.api.domain.SysDictType;
import com.ruoyi.system.mapper.DictTypeMapper;
import com.ruoyi.system.service.DictTypeService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, SysDictType> implements DictTypeService {
    @Override
    public IPage<SysDictType> selectDictTypeList(IPage<SysDictType> page, SysDictType dictType) {
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(SysDictType::getDictId,SysDictType::getDictName,SysDictType::getDictType,SysDictType::getStatus,SysDictType::getCreateBy,SysDictType::getCreateTime,SysDictType::getRemark);
        if (null!=dictType.getDictName() && !dictType.equals("")){
            wrapper.like(SysDictType::getDictName,dictType.getDictName());
        }
        if (null!=dictType.getStatus() && !dictType.getStatus().equals("")){
            wrapper.eq(SysDictType::getStatus,dictType.getStatus());
        }
        if (null!=dictType.getDictType() && !dictType.getDictType().equals("")){
            wrapper.like(SysDictType::getDictType,dictType.getDictType());
        }
        if (null!=dictType.getParams().get("beginTime") && null!=dictType.getParams().get("endTime")){
            wrapper.between(SysDictType::getCreateTime,dictType.getParams().get("beginTime"),dictType.getParams().get("endTime"));
        }
        return baseMapper.selectPage(page,wrapper);
    }

    @Override
    public boolean checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = baseMapper.selectOne(Wrappers.<SysDictType>lambdaQuery().eq(SysDictType::getDictType,dict.getDictType()));
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertDictType(SysDictType dict) {
        int row = baseMapper.insert(dict);
        if (row > 0) {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }
}
